<template>
  <div class="ds-sync-container">
    <el-card shadow="never">
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 同步配置 -->
        <el-tab-pane label="同步配置" name="config">
          <div class="toolbar">
            <el-button type="primary" @click="handleAddConfig">
              <icon-ic-round-plus class="mr-4px text-icon" />
              新增配置
            </el-button>
          </div>

          <el-table :data="configList" border stripe>
            <el-table-column prop="configName" label="配置名称" min-width="150" />
            <el-table-column prop="syncType" label="同步类型" width="120">
              <template #default="{ row }">
                <el-tag :type="getSyncTypeTag(row.syncType)">
                  {{ getSyncTypeLabel(row.syncType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="syncMode" label="同步模式" width="120">
              <template #default="{ row }">
                <el-tag :type="row.syncMode === 'AUTO' ? 'success' : 'info'">
                  {{ row.syncMode === 'AUTO' ? '自动' : '手动' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="syncInterval" label="同步间隔(秒)" width="120" />
            <el-table-column prop="enabled" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.enabled === 1 ? 'success' : 'danger'">
                  {{ row.enabled === 1 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="syncStatus" label="同步状态" width="120">
              <template #default="{ row }">
                <el-tag v-if="row.syncStatus" :type="getSyncStatusTag(row.syncStatus)">
                  {{ getSyncStatusLabel(row.syncStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="lastSyncTime" label="最后同步时间" width="180" />
            <el-table-column label="操作" width="250" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="handleTriggerSync(row.id)">
                  触发同步
                </el-button>
                <el-button link type="primary" @click="handleEditConfig(row)">
                  编辑
                </el-button>
                <el-button link type="danger" @click="handleDeleteConfig(row.id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            v-model:current-page="configPagination.pageNum"
            v-model:page-size="configPagination.pageSize"
            :total="configPagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="loadConfigList"
            @current-change="loadConfigList"
          />
        </el-tab-pane>

        <!-- 任务映射 -->
        <el-tab-pane label="任务映射" name="mapping">
          <el-table :data="mappingList" border stripe>
            <el-table-column prop="platformTaskName" label="平台任务" min-width="150" />
            <el-table-column prop="platformTaskType" label="任务类型" width="100" />
            <el-table-column prop="dsWorkflowName" label="DolphinScheduler工作流" min-width="180" />
            <el-table-column prop="dsWorkflowCode" label="工作流编码" width="150" />
            <el-table-column prop="mappingStatus" label="映射状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getMappingStatusTag(row.mappingStatus)">
                  {{ getMappingStatusLabel(row.mappingStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="syncStatus" label="同步状态" width="100">
              <template #default="{ row }">
                <el-tag v-if="row.syncStatus" :type="row.syncStatus === 'SYNCED' ? 'success' : 'warning'">
                  {{ row.syncStatus === 'SYNCED' ? '已同步' : '未同步' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="lastSyncTime" label="最后同步时间" width="180" />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="handleSyncWorkflow(row.dsWorkflowCode)">
                  同步状态
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            v-model:current-page="mappingPagination.pageNum"
            v-model:page-size="mappingPagination.pageSize"
            :total="mappingPagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="loadMappingList"
            @current-change="loadMappingList"
          />
        </el-tab-pane>

        <!-- 同步日志 -->
        <el-tab-pane label="同步日志" name="logs">
          <div class="toolbar">
            <el-form :inline="true">
              <el-form-item label="配置ID">
                <el-input v-model="logQuery.configId" placeholder="请输入配置ID" clearable />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="loadSyncLogs">
                  <icon-ic-round-search class="mr-4px text-icon" />
                  查询
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-table :data="logList" border stripe>
            <el-table-column prop="syncType" label="同步类型" width="120" />
            <el-table-column prop="syncAction" label="同步动作" width="150" />
            <el-table-column prop="sourceId" label="源对象ID" width="120" />
            <el-table-column prop="targetId" label="目标对象ID" width="120" />
            <el-table-column prop="syncStatus" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.syncStatus === 'SUCCESS' ? 'success' : 'danger'">
                  {{ row.syncStatus === 'SUCCESS' ? '成功' : '失败' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="duration" label="耗时(ms)" width="100" />
            <el-table-column prop="errorMessage" label="错误信息" min-width="200" show-overflow-tooltip />
            <el-table-column prop="createTime" label="创建时间" width="180" />
          </el-table>

          <el-pagination
            v-model:current-page="logPagination.pageNum"
            v-model:page-size="logPagination.pageSize"
            :total="logPagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="loadSyncLogs"
            @current-change="loadSyncLogs"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 同步配置对话框 -->
    <sync-config-modal
      v-model:visible="configModalVisible"
      :config-data="currentConfig"
      @success="handleConfigSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getSyncConfigList,
  getTaskMappingList,
  getSyncLogs,
  triggerSync,
  deleteSyncConfig,
  syncWorkflowStatus,
  type DsSyncConfig,
  type DsTaskMapping,
  type DsSyncLog
} from '@/service/api/dataplatform/ds-sync';
import SyncConfigModal from './modules/sync-config-modal.vue';

const activeTab = ref('config');

// 同步配置
const configList = ref<DsSyncConfig[]>([]);
const configPagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
});
const configModalVisible = ref(false);
const currentConfig = ref<DsSyncConfig | null>(null);

// 任务映射
const mappingList = ref<DsTaskMapping[]>([]);
const mappingPagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

// 同步日志
const logList = ref<DsSyncLog[]>([]);
const logPagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
});
const logQuery = reactive({
  configId: ''
});

onMounted(() => {
  loadConfigList();
  loadMappingList();
  loadSyncLogs();
});

// 加载同步配置列表
async function loadConfigList() {
  try {
    const res = await getSyncConfigList({
      pageNum: configPagination.pageNum,
      pageSize: configPagination.pageSize
    });
    configList.value = res.data.rows;
    configPagination.total = res.data.total;
  } catch (error) {
    ElMessage.error('加载同步配置失败');
  }
}

// 加载任务映射列表
async function loadMappingList() {
  try {
    const res = await getTaskMappingList({
      pageNum: mappingPagination.pageNum,
      pageSize: mappingPagination.pageSize
    });
    mappingList.value = res.data.rows;
    mappingPagination.total = res.data.total;
  } catch (error) {
    ElMessage.error('加载任务映射失败');
  }
}

// 加载同步日志
async function loadSyncLogs() {
  try {
    const res = await getSyncLogs({
      pageNum: logPagination.pageNum,
      pageSize: logPagination.pageSize,
      configId: logQuery.configId || undefined
    });
    logList.value = res.data.rows;
    logPagination.total = res.data.total;
  } catch (error) {
    ElMessage.error('加载同步日志失败');
  }
}

// 新增配置
function handleAddConfig() {
  currentConfig.value = null;
  configModalVisible.value = true;
}

// 编辑配置
function handleEditConfig(config: DsSyncConfig) {
  currentConfig.value = { ...config };
  configModalVisible.value = true;
}

// 删除配置
async function handleDeleteConfig(id: number) {
  try {
    await ElMessageBox.confirm('确认删除该同步配置吗？', '提示', {
      type: 'warning'
    });
    await deleteSyncConfig(id);
    ElMessage.success('删除成功');
    loadConfigList();
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
}

// 触发同步
async function handleTriggerSync(configId: number) {
  try {
    await triggerSync(configId);
    ElMessage.success('同步任务已触发');
    loadConfigList();
    loadSyncLogs();
  } catch (error) {
    ElMessage.error('触发同步失败');
  }
}

// 同步工作流状态
async function handleSyncWorkflow(workflowCode: number) {
  try {
    await syncWorkflowStatus(workflowCode);
    ElMessage.success('工作流状态同步成功');
    loadMappingList();
  } catch (error) {
    ElMessage.error('同步工作流状态失败');
  }
}

// 配置保存成功
function handleConfigSuccess() {
  loadConfigList();
}

// 获取同步类型标签
function getSyncTypeTag(type: string) {
  const map: Record<string, any> = {
    WORKFLOW: 'primary',
    TASK: 'success',
    INSTANCE: 'warning'
  };
  return map[type] || 'info';
}

// 获取同步类型标签文本
function getSyncTypeLabel(type: string) {
  const map: Record<string, string> = {
    WORKFLOW: '工作流',
    TASK: '任务',
    INSTANCE: '实例'
  };
  return map[type] || type;
}

// 获取同步状态标签
function getSyncStatusTag(status: string) {
  const map: Record<string, any> = {
    SUCCESS: 'success',
    FAILED: 'danger',
    RUNNING: 'warning',
    READY: 'info'
  };
  return map[status] || 'info';
}

// 获取同步状态标签文本
function getSyncStatusLabel(status: string) {
  const map: Record<string, string> = {
    SUCCESS: '成功',
    FAILED: '失败',
    RUNNING: '运行中',
    READY: '就绪'
  };
  return map[status] || status;
}

// 获取映射状态标签
function getMappingStatusTag(status: string) {
  const map: Record<string, any> = {
    ACTIVE: 'success',
    INACTIVE: 'warning',
    DELETED: 'danger'
  };
  return map[status] || 'info';
}

// 获取映射状态标签文本
function getMappingStatusLabel(status: string) {
  const map: Record<string, string> = {
    ACTIVE: '活跃',
    INACTIVE: '未激活',
    DELETED: '已删除'
  };
  return map[status] || status;
}
</script>

<style scoped lang="scss">
.ds-sync-container {
  padding: 16px;

  .toolbar {
    margin-bottom: 16px;
  }

  .el-pagination {
    margin-top: 16px;
    justify-content: flex-end;
  }
}
</style>
